/* $RCSFile: CRMImageODS.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageSettings/DAL/CRMImageODS.cs $
 * $log$
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;

using AddonNice.Core;
using AddonNice.Settings.Cache;
using AddonNice.Configuration;
using AddonNice.Security;
using AddonNice.Diagnostics;
using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.CRMImage;

using AddonNice.CRMImage;
using AddonNice.CRMImage.UI;

namespace AddonNice.Settings.CRMImage
{
    /// <summary>
    /// Object Data Source for Gridview that display images
    /// </summary>
    public class CRMImageListItem
    {
        #region Private Member Variables
        private int     _ImageId;
        private string  _adn_name            =   string.Empty;
        private Guid    _CrmImageId;
        private string  _ImageUrl           =   string.Empty;
        private string _shortDescription    =   string.Empty;
        private string _longDescription     =   string.Empty;
        private string _owner               =   string.Empty;
        private string _bu                  =   string.Empty;
        private DateTime _createdOn         =   DateTime.MinValue;
        #endregion
        
        public bool _isOk                   =   false;

        #region Constructors
        
        public CRMImageListItem() { }

        public CRMImageListItem(int wImageId, string wadn_name, Guid wCrmImageId, string wImageUrl, string wShortDescription)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItem Ctor wImageId: {0}, wadn_name: {1}, wCrmImageId: {2}, wImageUrl: {3}, wShortDescription: {4}.",
                new object[] { wImageId, wadn_name, wCrmImageId, wImageUrl, wShortDescription }),CrmImageTrace.Sw.Info);
            _ImageId            =   wImageId;
            _adn_name            =   wadn_name;
            _CrmImageId         =   wCrmImageId;
            _ImageUrl           =   wImageUrl;
            _shortDescription   =   wShortDescription;
        }
        #endregion

        #region Public Properties
        public int ImageId
        {
            get
            {
                return _ImageId;
            }
            set
            {
                _ImageId = value;
            }
        }
        
         public string adn_name
        {
            get
            {
                return _adn_name;
            }
            set
            {
                _adn_name = value;
            }
        }

        public string ShortDescription 
        {
            get
            {
                return _shortDescription;
            }
            set
            {
                if (value != null)
                    _shortDescription = value;
            }
        }

        public string LongDescription
        {
            get
            {
                return _longDescription;
            }
            set
            {
                if (value != null)
                    _longDescription = value;
            }
        }

        public string businessUnit
        {
            get
            {
                return _bu;
            }
            set
            {
                if ( value != null )
                    _bu = value;
            }
        }

        public string owner
        {
            get
            {
                return _owner;
            }
            set
            {
                if (value != null)
                    _owner = value;
            }
        }
        
        public DateTime createdOn
        {
            get
            {
                return _createdOn;
            }
            set
            {
                if (value != null)
                    _createdOn  =   value;
            }
        }
        
        public Guid CrmImageId
        {
            get
            {
                return _CrmImageId;
            }
            set
            {
                _CrmImageId = value;
            }

        }
        
        public string ImageUrl
        {
            get
            {
                return _ImageUrl;
            }
            set
            {
                _ImageUrl = value;
            }
        }
        
        #endregion

        /// <summary>
        /// Used to ensure that the wrapper in any DynEntity object is the current one, as they go in cache they need to refresh their wrapper 
        /// </summary>
        protected virtual void ResetWrapper(DynEntity dynEnt)
        {
            CRMWrapperBase  w   =   PortalSecurity.Wrapper;
            if ( !dynEnt.HasWrapper(w) )
                dynEnt.SetWrapper(w);
        }

        #region public methods
        
        public void InitializeFromReader(SqlDataReader reader)
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItem InitializeFromReader BEG at : {0}.", DateTime.UtcNow),CrmImageTrace.Sw.Info);
            
            ImageMetaData metadata  =   new ImageMetaData();
            metadata.LoadXml((string)reader[ImStr.DBMetadataXml]);
            ImageId                 =   Convert.ToInt32(reader[ImStr.DBImageId]);
            adn_name                =   metadata.GetMetadata(ImStr.ATCaption);
            ShortDescription        =   (string)reader[ImStr.DBShortDescription];
            CrmImageId              =   (Guid)(reader[ImStr.DBCrmImageId]);
	        if ( CrmImageTrace.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItem InitializeFromReader ImageId: '{0}', ShortDescription: '{1}', CrmImageId: '{2}'.",
                    new object[]{ImageId,ShortDescription,CrmImageId}),CrmImageTrace.Sw.Info);
            ImageUrl                =   metadata.GetMetadata(ImStr.ThumbnailFilename);
            LongDescription         =   metadata.GetMetadata(ImStr.DBLongDescription);
            // We get the corresponding entity from CRM and extract informations
            // We create the corresponding entity
            ADNDynImage im          =   DynEntity.GetFromCache<ADNDynImage>(ImStr.adnimage,PortalSecurity.Wrapper,ResetWrapper,CrmImageId,true);
            try
            {
                if ( im.Retrieved)
                {
                    adn_name        =   im.adn_name;
                    owner           =   im.ownerName;
                    businessUnit    =   im.owningbusinessunitName;
                    createdOn       =   im.createdonLocalDate;
			        if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItem InitializeFromReader Retrieved from CRM adn_name: {0}, owner: {1}, businessUnit: {2}, createdOn: {3}.",
                            new object[]{adn_name,owner,businessUnit,createdOn}),CrmImageTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
			    if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageListItem InitializeFromReader Retrieve from CRM failed ex : {0}.", ex),CrmImageTrace.Sw.Info);
                //throw;
                return;
            }
            _isOk                   =   true;
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( "[V]CRMImageListItem InitializeFromReader END.",CrmImageTrace.Sw.Info);
        }

        #endregion
    }
    
    /// <summary>
    /// Get all images without any selection from db images are included
    /// Get the corresponding CRM image entities to display the CRM name
    /// </summary>
    public class CRMImageListItemDAL
    {
        public static CRMImageListItem getImage(object anID)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItemDAL getImage anID: {0}.", anID),CrmImageTrace.Sw.Info);
            int ImageId     =   -1;
            if ( anID is int )
                ImageId     =   (int)anID;
            else
            {
                try
                {
                    ImageId =   int.Parse(anID.ToString());
                }
                catch (Exception ex)
                {
                    if ( CrmImageTrace.Sw.TraceError )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageListItemDAL getImage anID: {0}, ex: {1}", anID, ex),CrmImageTrace.Sw.Info);
                    throw;
                }
            }
            return getImages(ImageId);
        }
            
        public static CRMImageListItem getImages(int ImageId)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItemDAL getImages ImageId: {0}", ImageId),CrmImageTrace.Sw.Info);
            CRMImageListItem item   =   new CRMImageListItem();
            SqlDataReader reader    =   null;
            try
            {
                reader              =   new CRMImageDB().GetCRMImage(ImageId);
                if (reader.Read())
                {
                    item.InitializeFromReader(reader);
                }
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageListItemDAL GetImages ImageId: {0}, ex: {1}", ImageId,ex),CrmImageTrace.Sw.Info);
                throw;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
            return item;
        }


        public static void updateImage(CRMImageListItem ne)
        {
        }

        public static void deleteImage(CRMImageListItem ne) 
        { }

        public static List<CRMImageListItem> getImages(Guid CRMId, int ImageLibId)
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItemDAL List<CRMImageListItem> getImages enter CRMId: {0}.", CRMId),CrmImageTrace.Sw.Info);
            string ckey                     =   string.Format("CRMAllImages_{0}_{1}",CRMId,ImageLibId);
            if (CurrentCache.Exists(ckey))
            {
			    if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace.WriteLine("[V]CRMImageListItemDAL List<CRMImageListItem> getImages found in cache.",CrmImageTrace.Sw.Info);
                return (List<CRMImageListItem>)CurrentCache.Get(ckey);
            }


            List<CRMImageListItem> results  =   new List<CRMImageListItem>();
            SqlDataReader reader            =   null;
            try
            {
                reader                      =   new CRMImageDB().GetAllCRMImagesEx((Guid)CRMId,ImageLibId);

                // TODO modify the storeProc to remove already selected images for this entity from list
                while (reader.Read())
                {
                    CRMImageListItem item   =   new CRMImageListItem();
                    item.InitializeFromReader(reader);
          			if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageListItemDAL List<CRMImageListItem> getImages reading item adn_name: '{0}'.", item.adn_name),CrmImageTrace.Sw.Info);
                    if ( item._isOk )
                        results.Add(item);
                }
                CurrentCache.InsertMinutes(ckey, results,5);// 5 minutes
            }
            catch(Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageListItemDAL List<CRMImageListItem> getImages ex: {0}", ex),CrmImageTrace.Sw.Info);
                throw;
            }
            finally
            {
                if ( reader != null )
                    reader.Close();
            }
            return results;
        }
    }
}